package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.History;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.persistence.AccountDao;
import csu.web.mypetstore.persistence.impl.AccountDaoImpl;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {
    private static final String CART_FORM="/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*HttpSession session = req.getSession();
        String isAdd=session.getAttribute("isAdd").toString();
        String workingItemId=req.getParameter("workingItemId");
        Cart cart = (Cart) session.getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
        }
        if(isAdd.equals("true")){
            if(cart.containsItemId(workingItemId)){
                cart.incrementQuantityByItemId(workingItemId);
                //包含则增加
            }else {
                CatalogService catalogService = new CatalogService();
                boolean isInStock =catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                cart.addItem(item,isInStock);
            }
        }
        session.setAttribute("isAdd","false");
        session.setAttribute("cart", cart);

        //日志功能
        //session.setAttribute("product", product);
        session.setAttribute("item", workingItemId);

        //String productName=product.getName();
        String itemName=workingItemId;

        Account account = (Account) session.getAttribute("loginAccount");
        AccountDao accountDao=new AccountDaoImpl();

        boolean history=accountDao.findHistoryByUsernameandCategory(account.getUsername(),itemName);

        History history1=accountDao.getHistoryByUsername(account.getUsername(),itemName);
        if(!history|| history1.getVisittimes()==0){//找不到时getVisittimes()==0

            accountDao.insertHistroyUserId(account,itemName);
            accountDao.InitVisitNum(account,itemName);//赋值为0
            accountDao.initCartVisitNum(account,itemName);//赋值为0
            accountDao.insertHistroyUser(account,itemName);//插入商品编号
            accountDao.UpdateVisitNum(account,itemName);
            accountDao.UpdateCartVisitNum(account,itemName);
        }else{
            accountDao.UpdateCartVisitNum(account,itemName);
            accountDao.UpdateVisitNum(account,itemName);
        }*/
        //日志功能

        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }

    //日志功能会用到的方法


}
